<template>
	<view class="detail-container">
		<!-- 顶部图片轮播 -->
		<el-carousel class="cover-swiper" indicator-position="outside" height="500rpx">
			<el-carousel-item v-for="(img, index) in imageList" :key="index">
				<image class="cover-image" :src="baseUrl + img" mode="aspectFill"></image>
			</el-carousel-item>
		</el-carousel>

		<!-- 景点基本信息 -->
		<view class="info-section">
			<view class="title-row">
				<text class="title">{{attractionInfo.name}}</text>
				<view class="rating">
					<el-rate v-model="attractionInfo.averageRating" disabled :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
						:max="5" :disabled-void-color="'#C0C4CC'" size="large" />
					<text class="rating-text">{{attractionInfo.averageRating.toFixed(1)}}</text>
				</view>
			</view>

			<view class="meta-row">
				<view class="meta-item">
					<el-icon>
						<location />
					</el-icon>
					<text class="meta-text">{{attractionInfo.address}}</text>
				</view>
				<view class="meta-item">
					<el-icon>
						<clock />
					</el-icon>
					<text class="meta-text">开放时间: {{attractionInfo.openTime}}</text>
				</view>
				<view class="meta-item">
					<el-icon>
						<money />
					</el-icon>
					<text class="meta-text">门票: ¥{{attractionInfo.ticketPrice || '免费'}}</text>
				</view>
			</view>
		</view>

		<!-- 景点描述 -->
		<view class="section">
			<view class="section-title">景点介绍</view>
			<text class="description">{{attractionInfo.description}}</text>
		</view>

		<!-- 地图位置 -->
		<!-- <view class="section">
			<view class="section-title">位置信息</view>
			<map class="map-container" :latitude="attractionInfo.latitude" :longitude="attractionInfo.longitude"
				:markers="markers" show-location></map>
		</view> -->

		<!-- 使用 Element Plus 的评论输入区域 -->
		<!-- <view class="comment-input-section">
			<el-card class="comment-card">
				<el-input v-model="newComment" type="textarea" :rows="4" placeholder="写下您的游览体验..." maxlength="200"
					show-word-limit></el-input>

				<view class="input-footer">
					<el-rate v-model="newRating" class="rating-input"></el-rate>
					<el-button type="primary" @click="submitComment" :loading="isSubmitting"
						:disabled="!newComment.trim()">
						发表评论
					</el-button>
				</view>
			</el-card>
		</view> -->

		<!-- 引入评论发布组件 -->
		<leave-review v-if="showReviewInput && attractionInfo.attractionId"
			:attractionId="Number(attractionInfo.attractionId)" @review-submitted="handleReviewSubmitted">
		</leave-review>



		<!-- 评论组件 -->
		<review-info v-if="attractionInfo && attractionInfo.attractionId" :reviews="reviews" :base-url="baseUrl"
			@review-deleted="handleReviewDelete" :attractionId="Number(attractionInfo.attractionId)"></review-info>

		<!-- 底部操作栏 -->
		<view class="footer-bar">
			<!-- <view class="action-btn" @click="navigateToMap">
				<el-icon>
					<location />
				</el-icon>
				<text>导航</text>
			</view> -->
			<view class="action-btn" @click="toggleCollection">
				<el-icon :color="isCollected ? '#FF5A5F' : '#666'">
					<component :is="isCollected ? 'star-filled' : 'star'" />
				</el-icon>
				<text>{{isCollected ? '已收藏' : '收藏'}}</text>
			</view>
			<!-- <el-button class="buy-btn" type="danger" @click="handleBuyTicket">购票</el-button> -->
			<el-button class="buy-btn" type="primary" @click="checkLoginBeforeReview" v-if="!showReviewInput">
				<el-icon>
					<Edit />
				</el-icon>
				<span>写评价</span>
			</el-button>

		</view>
	</view>
</template>


<script>
	import {
		getData,
		getParams,
		postData,
		deleteParams
	} from '@/axios/http';
	import base from "/axios/base.js";
	import {
		ElCarousel,
		ElCarouselItem,
		ElRate,
		ElIcon,
		ElButton
	} from 'element-plus';
	import {
		Location,
		Clock,
		Money,
		Star,
		StarFilled,
		Edit
	} from '@element-plus/icons-vue';
	import ReviewInfo from './comment/reviewInfo.vue'; // 导入评论组件
	import LeaveReview from './comment/LeaveReview.vue'; // 导入发布评论组件

	export default {
		components: {
			ElCarousel,
			ElCarouselItem,
			ElRate,
			ElIcon,
			ElButton,
			Location,
			Clock,
			Money,
			Star,
			StarFilled,
			ReviewInfo,
			LeaveReview,
			Edit // 注册图标组件
		},
		data() {
			return {
				attractionInfo: {
					attractionId: null, // 明确初始化，子组件要用
					name: '',
					address: '',
					description: '',
					averageRating: 0,
					openTime: '',
					ticketPrice: 0,
					latitude: 0,
					longitude: 0,
					coverImage: '',
					detailImages: null
				},
				baseUrl: '',
				isCollected: false, //是否收藏
				// markers: [],
				reviews: [],
				showReviewInput: false, // 控制是否显示评论输入框
			}
		},
		computed: {
			imageList() {
				const images = [this.attractionInfo.coverImage];
				if (this.attractionInfo.detailImages) {
					return images.concat(this.attractionInfo.detailImages);
				}
				return images;
			}
		},
		async onReady() {
			// console.log("onReady钩子，只加载一次")
			// console.log("onReady钩子options：",options)
			
		},
		async onLoad(options) {
			let url = '/attraction/' + options.id;
			this.baseUrl = base.url;

			await this.loadData(url);
			// 将字符串数组转换成数组
			this.attractionInfo.detailImages = JSON.parse(this.attractionInfo.detailImages);

			// console.log("子组件已加载")
			
			//如果用户已登录则添加用户浏览记录
			if (uni.getStorageSync('LoginUser')) {
				// console.log("用户已登录")
				let data = {
					userId: uni.getStorageSync('LoginUser').userId,
					attractionId: options.id
				}
				// console.log("要发送的数据", data)
				const res = await postData('/view', data)
				// console.log("返回的res", res)
				if (res.status != 200) {
					console.error("请求失败", res.data.message)
				}
			}
			
			//地图相关
			// this.markers = [{
			// 	id: 1,
			// 	latitude: this.attractionInfo.latitude,
			// 	longitude: this.attractionInfo.longitude,
			// 	title: this.attractionInfo.name,
			// 	iconPath: '/static/location.png',
			// 	width: 30,
			// 	height: 30
			// }];
		},
		methods: {
			//删除评论
			async handleReviewDelete(index) {
				// console.log("子组件点击删除：index：",index)
				await this.reqReview()
			},

			// 修改：添加检查登录状态
			checkLoginBeforeReview() {
				if (!uni.getStorageSync('LoginUser')) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return false;
				}
				this.showReviewInput = true;
				return true;
			},

			// 新增：处理评论提交成功
			async handleReviewSubmitted(data) {
				// 刷新评论信息
				try {
					uni.showLoading({
						title: '更新数据中...'
					});
					await this.reqReview(); // 使用专用方法
					this.showReviewInput = false;
				} catch (error) {
					console.error('更新失败:', error);
				} finally {
					uni.hideLoading();
				}
			},



			//请求评论信息
			async reqReview() {
				const reviewUrl = '/reviews/' + this.attractionInfo.attractionId;
				// console.log("评论请求的url", reviewUrl);

				const resReviews = await getData(reviewUrl);
				// console.log("评论信息", resReviews.data.reviews);
				if (resReviews.data.code === 200) {
					this.reviews = resReviews.data.reviews.map(review => ({
						...review,
						avatarUrl: review.avatarUrl || '/static/default-avatar.JPG',
						reviewCreatedAt: review.reviewCreatedAt || review.createdAt || new Date()
							.toISOString(),
						rating: Number(review.rating) || 0
					}));
				}
			},

			//加载数据
			async loadData(url) {
				uni.showLoading({
					title: '加载中'
				});

				try {
					const resAttraction = await getData(url);
					// 检查景点数据是否加载成功
					if (resAttraction.data.code !== 200) {
						throw new Error(resAttraction.data.message || '景点加载失败');
					}

					// this.attractionInfo = resAttraction.data.attractions[0];
					this.attractionInfo = {
						...resAttraction.data.attractions[0],
						// 强制转换为数字，失败时设为0（可根据需求调整）
						attractionId: Number(resAttraction.data.attractions[0].attractionId) || 0
					};
					// console.log("loadDate下的this.attractionInfo:", this.attractionInfo)
					//如果该景点有评论信息
					if (this.attractionInfo.reviewCount) {
						// // 请求评论信息
						await this.reqReview();
					}
					this.checkCollectionStatus();
					uni.hideLoading();

				} catch (error) {
					uni.showToast({
						title: '加载失败',
						icon: 'none',
						duration: 2000
					});
				} finally {
					uni.hideLoading();
				}

			},

			//获取收藏状态
			async checkCollectionStatus() {
				try {
					// 1. 检查必要参数是否存在
					const loginUser = uni.getStorageSync('LoginUser');
					if (!loginUser || !loginUser.userId) {
						console.error('用户未登录或用户ID无效');
						this.isCollected = false;
						return;
					}

					if (!this.attractionInfo || !this.attractionInfo.attractionId) {
						console.error('景点信息不完整');
						this.isCollected = false;
						return;
					}

					// 2. 准备请求数据
					const data = {
						userId: loginUser.userId,
						attractionId: this.attractionInfo.attractionId
					};
					// console.log("请求参数：", data);

					// 3. 发起API请求
					const res = await getParams('/favorite', data);

					// console.log("res：", res);

					// 4. 处理响应数据
					if (!res) {
						throw new Error('API返回空响应');
					}

					if (res.status !== 200) {
						throw new Error(`API请求失败，状态码：${res.statusCode}`);
					}

					if (res.data && res.data.favorite !== null) {
						this.isCollected = true;
					} else {
						this.isCollected = false;
					}

				} catch (error) {
					console.error('检查收藏状态时出错：', error.message || error);
					this.isCollected = false;

					// 可以根据不同的错误类型进行特殊处理
					if (error.message.includes('Network Error')) {
						uni.showToast({
							title: '网络连接失败',
							icon: 'none'
						});
					} else {
						uni.showToast({
							title: '获取收藏状态失败',
							icon: 'none'
						});
					}
				}
			},
			//收藏按钮
			async toggleCollection() {

				// 1. 检查必要参数是否存在
				const loginUser = uni.getStorageSync('LoginUser');
				if (!loginUser || !loginUser.userId) {
					console.error('用户未登录或用户ID无效');
					this.isCollected = false;
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				// 如果是收藏的
				if (this.isCollected) {
					// 取消收藏
					try {
						const res = await deleteParams('/favorite', {
							userId: loginUser.userId,
							attractionId: this.attractionInfo.attractionId
						});
						// console.log("取消收藏返回的数据", res);
						if (res.data.code === 200) {
							this.isCollected = false;
							uni.showToast({
								title: '已取消收藏',
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							});
						}

					} catch (error) {
						console.error("取消收藏失败:", error);
						uni.showToast({
							title: '取消收藏失败',
							icon: 'error'
						});
					}
				} else { // 未收藏
					let data = {
						userId: loginUser.userId,
						attractionId: this.attractionInfo.attractionId
					}

					// console.log("收藏的数据", data);

					try {
						//更新用户收藏
						const resFavorite = await postData('/favorite', data);
						//更新用户行为
						const resUserBehavior = await postData('/collect', data);
						// console.log("收藏返回的数据", resFavorite);
						if (resFavorite.data.code === 200) {
							this.isCollected = true;
							uni.showToast({
								title: '已收藏',
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: resFavorite.data.message,
								icon: 'error'
							});

						}
						if (resUserBehavior.status != 200) {
							console.error("请求失败", res.data.message)
						}

					} catch (error) {
						console.error("收藏失败:", error);
						uni.showToast({
							title: '收藏失败',
							icon: 'none'
						});
					}
				}
			},

			//地图相关
			// navigateToMap() {
			// 	uni.openLocation({
			// 		latitude: this.attractionInfo.latitude,
			// 		longitude: this.attractionInfo.longitude,
			// 		name: this.attractionInfo.name,
			// 		address: this.attractionInfo.address
			// 	});
			// },

			handleBuyTicket() {
				uni.showModal({
					title: '购票提示',
					content: `确定购买${this.attractionInfo.name}门票，票价¥${this.attractionInfo.ticketPrice}吗？`,
					success: (res) => {
						if (res.confirm) {
							uni.showToast({
								title: '购票成功',
								icon: 'success'
							});
						}
					}
				});
			}
		}
	}
</script>


<style lang="scss">
	.detail-container {
		padding-bottom: 100rpx;
		background-color: #f5f5f5;

		.cover-swiper {
			.cover-image {
				width: 100%;
				height: 100%;
			}
		}

		.info-section {
			padding: 30rpx;
			background-color: #fff;
			margin-bottom: 20rpx;

			.title-row {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;

				.title {
					font-size: 36rpx;
					font-weight: bold;
					color: #333;
				}

				.rating {
					display: flex;
					align-items: center;

					.el-rate {
						height: 30rpx;
					}

					.rating-text {
						font-size: 28rpx;
						color: #FF9900;
						margin-left: 10rpx;
					}
				}
			}

			.meta-row {
				.meta-item {
					display: flex;
					align-items: center;
					margin-bottom: 15rpx;
					font-size: 26rpx;
					color: #666;

					.el-icon {
						font-size: 32rpx;
						margin-right: 10rpx;
					}
				}
			}
		}

		.section {
			background-color: #fff;
			padding: 30rpx;
			margin-bottom: 20rpx;

			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 20rpx;
				position: relative;
				padding-left: 20rpx;

				&::before {
					content: '';
					position: absolute;
					left: 0;
					top: 50%;
					transform: translateY(-50%);
					width: 8rpx;
					height: 30rpx;
					background-color: #007AFF;
					border-radius: 4rpx;
				}
			}

			.description {
				font-size: 28rpx;
				color: #666;
				line-height: 1.6;
			}
		}

		.map-container {
			width: 100%;
			height: 400rpx;
			border-radius: 10rpx;
		}

		.footer-bar {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			height: 100rpx;
			background-color: #fff;
			display: flex;
			align-items: center;
			box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
			padding: 0 20rpx;

			.action-btn {
				flex: 1;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
				color: #666;

				.el-icon {
					font-size: 40rpx;
					margin-bottom: 5rpx;
				}
			}

			.buy-btn {
				flex: 2;
				border-radius: 50rpx;
				margin-left: 20rpx;
				height: 80rpx;
			}
		}
	}
</style>